/*
 * This service is used to communicate with bluetooth LE devices. 
 * It can only process data from LE heartrate devices. Broadcasts any changes it detects.
 */

package jens.nordmark.smartheartratemonitor;

import java.util.List;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BluetoothLeService extends Service{

    private BluetoothAdapter myBluetoothAdapter;
    private String myBluetoothDeviceAddress;
    private BluetoothGatt myBluetoothGatt;
    public int myConnectionState = STATE_DISCONNECTED;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;
    
    public final static String ACTION_GATT_CONNECTED = "jens.nordmark.smartheartratemonitor.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "jens.nordmark.smartheartratemonitor.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "jens.nordmark.smartheartratemonitor.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "jens.nordmark.smartheartratemonitor.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA = "jens.nordmark.smartheartratemonitor.EXTRA_DATA";
    public final static String WRONG_DEVICE = "jens.nordmark.smartheartratemonitor.WRONG_DEVICE";
    
    public static UUID CLIENT_CHARACTERISTIC_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    public static UUID UUID_HEART_RATE_SERVICE = UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb");
    public static UUID UUID_HEART_RATE_CHARACTERISTIC = UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb");
    
    /*
     * Called whenever some change occurs to the connection.
     */
    private final BluetoothGattCallback myGattCallback =
    new BluetoothGattCallback() {
    	
    	/*
    	 * Triggered when connecting/disconnecting.
    	 */
    	public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    		String intentAction;
    		Log.d("BTLEService","onConnectionStateChange 1");
    		if (newState == BluetoothProfile.STATE_CONNECTED){
    			Log.d("BTLEService","onConnectionStateChange Connected");
    			intentAction = ACTION_GATT_CONNECTED;
    			myConnectionState = STATE_CONNECTED;
    	        boolean discovery = myBluetoothGatt.discoverServices();
    	        Log.d("BTLEService","onConnectionStateChange Servicediscovery: " + Boolean.toString(discovery));
    			broadcastUpdate(intentAction);
    		}
    		if (newState == BluetoothProfile.STATE_DISCONNECTED){
    			Log.d("BTLEService","onConnectionStateChange Disconnected");
    			intentAction = ACTION_GATT_DISCONNECTED;
    			myConnectionState = STATE_DISCONNECTED;
    			broadcastUpdate(intentAction);
    		}
    	}
    	
    	/*
    	 * Triggered when BluetoothGatt.getServices finds something.
    	 */
    	public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    		if (status == BluetoothGatt.GATT_SUCCESS) {
    			Log.d("BTLEService","onServicesDiscovered 1");
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    		}
    	}
    	
    	/*
    	 * Triggered when BluetoothGatt.readCharacteristic finds something.
    	 */
    	public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) {
    		Log.d("BTLEService","onCharacteristicRead 1");
    		if (status == BluetoothGatt.GATT_SUCCESS) {
    			Log.d("BTLEService","onCharacteristicRead 2");
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
    	}
    	
    	/*
    	 * Triggered when a device notifies the bluetooth adapter of a change in a characteristic.
    	 * Use setCharacteristicNotification to enable these notifications.
    	 */
    	public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
    		Log.d("BTLEService","onCharacteristicChanged 1");
    		broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    		Log.d("BTLEService","onCharacteristicChanged 2");
    	}
    };
    
    /*
     * Sets the characteristic notification property for a certain characteristic. The app will then be
     * notified when this characteristic changes. When notifications are received the
     * onCharacteristicChanged method of the BluetoothGattCallback is triggered.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
            boolean enabled) {
    	myBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    	Log.d("BluetoothLeService.setCharacteristicNotification UUID",characteristic.getUuid().toString());
    	BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
    	descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    	myBluetoothGatt.writeDescriptor(descriptor);
    }
    
    /*
     * Requests data from the device, when an answer is received the onCharacteristicRead method in the
     * BluetoothGattCallback is triggered.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    	myBluetoothGatt.readCharacteristic(characteristic);
    }
    
    /*
     * Generic broadcasting function.
     */
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }
    
    /*
     * Checks the BluetoothGattcharacteristic given to it and broadcasts the heartrate if the
     * UUID found in the characteristic is correct. Otherwise broadcasts an error message.
     */
    private void broadcastUpdate(final String action,
            final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);
        if (UUID_HEART_RATE_CHARACTERISTIC.equals(characteristic.getUuid())) {
        	int flag = characteristic.getProperties();
            int format = -1;
            if ((flag & 0x01) != 0) {
                format = BluetoothGattCharacteristic.FORMAT_UINT16;
            } else {
                format = BluetoothGattCharacteristic.FORMAT_UINT8;
            }
            final int heartRate = characteristic.getIntValue(format, 1);
            intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
        	sendBroadcast(intent);
        }
        else
        {
        	intent.putExtra(WRONG_DEVICE, characteristic.getUuid().toString());
        	sendBroadcast(intent);
        }
    }
    
    /*
     * Attempts to connect to the specified address, returns true if successful and false otherwise.
     */
    public boolean connect(final String address) {
    	Log.d("BluetoothLeService.connect","1");
    	
        if (address == null) {
        	Log.d("BluetoothLeService.connect", "address is null");
            return false;
        }
        if (myBluetoothAdapter == null ) {
        	Log.d("BluetoothLeService.connect", "no bluetoothadapter");
            return false;
        }
        
        Log.d("BluetoothLeService.connect","2");
        if (myBluetoothDeviceAddress != null && address.equals(myBluetoothDeviceAddress)
                && myBluetoothGatt != null) {
            if (myBluetoothGatt.connect()) {
                myConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }
        Log.d("BluetoothLeService.connect","3");
        final BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            return false;
        }
        Log.d("BluetoothLeService.connect","4");
        myBluetoothGatt = device.connectGatt(this, false, myGattCallback);
        myBluetoothDeviceAddress = address;
        myConnectionState = STATE_CONNECTING;
        return true;
    }
    
    /*
     * Disconnects from the device if connected, does nothing if not connected.
     */
    public void disconnect() {
        if (myBluetoothAdapter == null || myBluetoothGatt == null) {
            Log.w("disconnect", "BluetoothAdapter not initialized");
            return;
        }
        myBluetoothGatt.disconnect();
    }
    
    /*
     * Makes sure there is a bluetoothadapter available, gets it and sets myBluetoothadapter to be
     * that adapter.
     */
    public boolean initialize() {
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Log.d("Initialize BT", myBluetoothAdapter.getName());
        if (myBluetoothAdapter == null) {
        	Log.d("Initialize BT", "Failed");
            return false;
        }
        Log.d("Initialize BT", "Success");
        return true;
    }
    
    /*
     * --------------------------------------------------------------------------------------------
     * The following four functions are for handling the connection between the service and the UI.
     */
	@Override
	public IBinder onBind(Intent intent) {
		return myBinder;
	}

	@Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }
    
    public class LocalBinder extends Binder {
        BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    private final IBinder myBinder = new LocalBinder();
    
    public void close() {
        if (myBluetoothGatt == null) {
            return;
        }
        myBluetoothGatt.close();
        myBluetoothGatt = null;
    }
    /*
     * --------------------------------------------------------------------------------------------
     */
    
    /*
     * This function returns a List of the services supported by the presently connected device.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (myBluetoothGatt == null){
        	Log.d("BluetoothLeService.getSupportedGattServices","myBluetoothGatt is null");
        	return null;
        }

        Log.d("BluetoothLeService.getSupportedGattServices","returning services");
        Log.d("Services:",myBluetoothGatt.getServices().toString());
        return myBluetoothGatt.getServices();
    }
}
